package net.sf.midollo.net.httptunnel.client;

import net.sf.midollo.io.IOStreamFactory;

import java.io.IOException;
import java.net.URL;

public class HttpTunnelConnection {

	protected final URL url;
	protected final IOStreamFactory ioStreamFactory;
	protected HttpTunnelClient client;
	protected HttpTunnelClientInputStream is;
	protected HttpTunnelClientOutputStream os;

	public HttpTunnelConnection(URL url, IOStreamFactory ioStreamFactory) {
		this.url = url;
		this.ioStreamFactory = ioStreamFactory;
	}

	public synchronized void connect() throws IOException {
		String uri = this.url.getFile();
		if (uri.startsWith("/http"))
			uri = uri.substring(1);
		this.client = new HttpTunnelClient(this.ioStreamFactory, uri);
		this.is = new HttpTunnelClientInputStream(this.client);
		this.os = new HttpTunnelClientOutputStream(this.client);
	}

	public synchronized void disconnect() throws IOException {
		this.client.close();
	}

	public HttpTunnelClientInputStream getInputStream() throws IOException {
		return this.is;
	}

	public HttpTunnelClientOutputStream getOutputStream() throws IOException {
		return this.os;
	}
}
